package com.zzz.springsecuritystudy.security;

import com.zzz.springsecuritystudy.entity.ResponseResult;
import com.zzz.springsecuritystudy.util.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 匿名未登录的时候访问，遇到需要登录认证的时候被调用
 *
 * @date 2021/9/15
 */
@Component
@Slf4j
public class EntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        // 当用户尝试访问安全的REST资源而不提供任何凭据时，将调用此方法发送401 响应
        log.info(e.getMessage());
        ResponseUtils.print(response,new ResponseResult(HttpServletResponse.SC_UNAUTHORIZED,e.getMessage(),null));
    }

}